import random

from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from verifications import constants
import logging

logger = logging.getLogger('django')
from meiduo_mall.libs.yuntongxun.sms import CCP


# 地址
# /sms_codes/(?P<mobile>1[3-9]\d{9})/
class SMSCodeView(APIView):
    """
    获取短信验证码
    """

    def get(self, request, mobile):

        # 一开始先判断60秒内是否发送过短信验证码
        conn = get_redis_connection('verify_codes')

        send_flag = conn.get('send_flag_%s' % mobile)

        if send_flag:
            return Response({'message: 发送短信频繁'}, status=status.HTTP_400_BAD_REQUEST)

        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)

        # 使用redis pipline,减少链接次数,一次连接,完成多个任务
        pl = conn.pipeline()

        # 向pipline添加任务
        # 设置过期时间
        pl.set('sms_code_%s' % mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRES)

        # 添加60秒发送间隔校验,
        pl.set('send_flag_%s' % mobile, 1, constants.SEND_SMS_CODE_INTERVAL)

        # 执行pipline提交
        pl.execute()

        expire = constants.SMS_CODE_REDIS_EXPIRES // 60

        # 发出发送短信任务
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, expire, sms_code)

        logger.info('短信验证码是 %s' % sms_code)

        return Response({'message': 'OK'})
